import time

import requests
import MySQLdb
from MySQLdb import OperationalError

# 配置数据库
db_config = {
    'host': 'localhost',
    'user': 'root',       # 替换为你的用户名
    'password': '',   # 替换为你的密码
    'database': 'bilibili',   # 替换为你的数据库名
    'port': 3307,
    'autocommit': True             # 自动提交事务
}

url = "https://api.bilibili.com/pgc/season/index/result"
params = {
    "st": "1",
    "order": "3",
    "season_version": "-1",
    "spoken_language_type": "-1",
    "area": "-1",
    "is_finish": "-1",
    "copyright": "-1",
    "season_status": "-1",
    "season_month": "-1",
    "year": "-1",
    "style_id": "-1",
    "sort": "0",
    "page": "1",
    "season_type": "1",
    "pagesize": "20",
    "type": "1"
}

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0"
}

try:
    # 建立数据库连接
    conn = MySQLdb.connect(**db_config)
    cursor = conn.cursor()
    print("数据库连接成功")

    cache_data_list = []
    # 数据的爬取
    for page in range(1, 202):
        params["page"] = page
        response = requests.get(url, headers=headers, params=params)
        if response.status_code == 200:
            for item in response.json().get("data").get("list"):
                title = item.get("title")
                watch = item.get("order")
                picture_link = item.get("cover")
                link = item.get("link")
                cache_data_list.append([title, watch, picture_link, link])
    if cache_data_list:

        print(f"成功插入 {len(cache_data_list)} 条数据")
    else:
        print("没有数据可插入")

except OperationalError as e:
    print(f"数据库操作错误: {str(e)}")
except Exception as e:
    print(f"发生未知错误: {str(e)}")
finally:
    # 关闭资源
    if conn:
        cursor.close()
        conn.close()
        print("数据库连接已关闭")





